package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper,Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    public Employee login(Employee employee) {
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<Employee>();
        queryWrapper.eq(employee != null, Employee::getUsername, employee.getUsername());
        //将加密后的密码传输过去
        String password=DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        queryWrapper.eq(employee != null, Employee::getPassword, password);
        return employeeMapper.selectOne(queryWrapper);
    }

    @Override
    public IPage<Employee> getAllEmployeesByPage(Integer page, Integer pageSize, String name) {
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<Employee>();
        //条件判断
        queryWrapper.like(name !=null,Employee::getName,name);
        IPage<Employee> iPage=new Page<>();
        iPage.setCurrent(page);
        iPage.setSize(pageSize);
        return employeeMapper.selectPage(iPage, queryWrapper);
    }

    @Override
    public Integer addEmployee(Employee employee) {
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<Employee>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee employee1=employeeMapper.selectOne(queryWrapper);
        if (employee1 != null) {
            //用户名已存在
            return 2;
        }

        return employeeMapper.insert(employee);
    }

    @Override
    public Employee getEmployeeById(Long id) {
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<Employee>();
        queryWrapper.eq(Employee::getId, id);
        return employeeMapper.selectOne(queryWrapper);
    }

    @Override
    public Boolean updateEmployee(Employee employee) {
        return employeeMapper.updateById(employee) > 0;
    }

}
